package com.x.erp.dao;

import com.x.erp.model.ImageView;
import com.x.framework.dao.BaseDao;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片场景信息DAO
 */
@Repository
public class ImageViewDao extends BaseDao {

	private final static String selectImageViewListSql = "SELECT biv.* FROM BASE_IMAGE_VIEW biv WHERE 1=1 ";
	/**
	 * 查询图片场景列表
	 * @param imageView
	 * @return
	 * @throws Exception
	 */
	public List<ImageView> selectImageViewList(ImageView imageView) throws Exception{
		StringBuilder sql = new StringBuilder(selectImageViewListSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, imageView);
		sql.append("ORDER BY biv.IMAGE_VIEW_ID ASC ");
		return this.queryForList(sql.toString(), ImageView.class, params, imageView);
	}

	private final static String selectImageViewSql = "SELECT biv.*, " +
			"bivt.IMAGE_TYPE_KEY " +
			"FROM BASE_IMAGE_VIEW biv " +
			"JOIN base_image_view_type bivt ON biv.IMAGE_VIEW_ID = bivt.IMAGE_VIEW_ID " +
			"WHERE 1=1 ";
	/**
	 * 查询图片场景
	 * @param imageView
	 * @return
	 * @throws Exception
	 */
	public List<ImageView> selectImageViewListById(ImageView imageView) throws Exception{
		StringBuilder sql = new StringBuilder(selectImageViewSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, imageView);
		return this.queryForList(sql.toString(), ImageView.class, params);
	}

	private final static String selectImageViewNumSql = "SELECT COUNT(biv.IMAGE_VIEW_ID) FROM BASE_IMAGE_VIEW biv WHERE 1=1 ";
	/**
	 * 查询图片场景数量
	 * @param imageView
	 * @return
	 * @throws Exception
	 */
	public int selectImageViewNum(ImageView imageView) throws Exception{
		StringBuilder sql = new StringBuilder(selectImageViewNumSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, imageView);
		return this.queryForInt(sql.toString(), params);
	}

	/**
	 * 查询条件
	 * @param sql
	 * @param params
	 * @param imageView
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, ImageView imageView) {
		if(imageView != null) {
			if(StringUtils.isNotEmpty(imageView.getImageViewName())){
				sql.append("AND biv.IMAGE_VIEW_NAME = ? ");
				params.add(imageView.getImageViewName());
			}
			if(imageView.getImageViewId() != null){
				sql.append("AND biv.IMAGE_VIEW_ID = ? ");
				params.add(imageView.getImageViewId());
			}
		}
	}
}
